package com.example.casper.Experiment2024;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.casper.Experiment2024.items.Location;
import com.tencent.lbssearch.TencentSearch;
import com.tencent.lbssearch.httpresponse.BaseObject;
import com.tencent.lbssearch.httpresponse.HttpResponseListener;
import com.tencent.lbssearch.object.param.DistrictChildrenParam;
import com.tencent.lbssearch.object.result.DistrictResultObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class locationDetailsInputActivity extends AppCompatActivity {

    private Spinner spinnerProvince;
    private Spinner spinnerCity;
    private Spinner spinnerDistrict;
    private EditText editTextFeeling;
    private Uri currentImageUri;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location_input_details);
        spinnerProvince = findViewById(R.id.spinner_province);
        spinnerCity = findViewById(R.id.spinner_city);
        spinnerDistrict = findViewById(R.id.spinner_district);
        editTextFeeling = findViewById(R.id.edittext_location_feeling);

        // 获取传入的数据
        Location location = (Location) getIntent().getSerializableExtra("location");
        int position = getIntent().getIntExtra("position", 0);

        if (location != null) {
            // 初始化字段
            editTextFeeling.setText(location.getFeeling());
            // 图片保持不变，仅显示
            currentImageUri = location.getPicPath();
        }

        // 默认加载所有省的数据
        getProvinceData();

        Button buttonOK = findViewById(R.id.button_item_details_ok);
        buttonOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent returnIntent = new Intent();
                String province = spinnerProvince.getSelectedItem().toString();
                String city = spinnerCity.getSelectedItem().toString();
                String district = spinnerDistrict.getSelectedItem().toString();
                String feeling = editTextFeeling.getText().toString();

                returnIntent.putExtra("position", getIntent().getIntExtra("position", 0));
                returnIntent.putExtra("province_name", province);
                returnIntent.putExtra("city_name", city);
                returnIntent.putExtra("district_name", district);
                returnIntent.putExtra("feeling", feeling);
                returnIntent.putExtra("PicPath", currentImageUri );
                setResult(RESULT_OK, returnIntent);
                finish();
            }
        });
    }

    // 获取省份数据
    private void getProvinceData() {
        TencentSearch tencentSearch = new TencentSearch(this);
        DistrictChildrenParam districtChildrenParam = new DistrictChildrenParam();
        districtChildrenParam.id(0);  // id 为 0 表示获取所有省份/直辖市数据

        tencentSearch.getDistrictChildren(districtChildrenParam, new HttpResponseListener<BaseObject>() {
            @Override
            public void onSuccess(int statusCode, BaseObject responseObject) {
                if (responseObject == null) {
                    return;
                }

                DistrictResultObject obj = (DistrictResultObject) responseObject;
                List<String> provinces = new ArrayList<>();
                List<Integer> provinceIds = new ArrayList<>();
                List<DistrictResultObject.DistrictResult> districtResults = obj.result.get(0);

                for (DistrictResultObject.DistrictResult result : districtResults) {
                    provinces.add(result.fullname);
                    provinceIds.add(result.id);
                }

                // 设置省份适配器
                ArrayAdapter<String> provinceAdapter = new ArrayAdapter<>(locationDetailsInputActivity.this,
                        android.R.layout.simple_spinner_item, provinces);
                provinceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinnerProvince.setAdapter(provinceAdapter);

                // 监听省份选择变化，加载对应的城市
                spinnerProvince.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        int selectedProvinceId = provinceIds.get(position);
                        getCityData(selectedProvinceId);  // 加载对应省份的城市数据
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                        spinnerCity.setAdapter(null);  // 清空城市选择
                        spinnerDistrict.setAdapter(null);  // 清空区选择
                    }
                });
            }

            @Override
            public void onFailure(int statusCode, String message, Throwable error) {
                Log.e("test", "error code:" + statusCode + ", msg:" + message);
                Toast.makeText(locationDetailsInputActivity.this, "Failed to load province data: " + message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    // 获取城市数据
    private void getCityData(int provinceId) {
        TencentSearch tencentSearch = new TencentSearch(this);
        DistrictChildrenParam districtChildrenParam = new DistrictChildrenParam();
        districtChildrenParam.id(provinceId);  // 根据选中的省份 id 获取城市

        tencentSearch.getDistrictChildren(districtChildrenParam, new HttpResponseListener<BaseObject>() {
            @Override
            public void onSuccess(int statusCode, BaseObject responseObject) {
                if (responseObject == null) {
                    return;
                }

                DistrictResultObject obj = (DistrictResultObject) responseObject;
                List<String> cities = new ArrayList<>();
                List<Integer> cityIds = new ArrayList<>();
                List<DistrictResultObject.DistrictResult> districtResults = obj.result.get(0);

                for (DistrictResultObject.DistrictResult result : districtResults) {
                    cities.add(result.fullname);
                    cityIds.add(result.id);
                }

                // 设置城市适配器
                ArrayAdapter<String> cityAdapter = new ArrayAdapter<>(locationDetailsInputActivity.this,
                        android.R.layout.simple_spinner_item, cities);
                cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinnerCity.setAdapter(cityAdapter);

                // 监听城市选择变化，加载对应的区数据
                spinnerCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        int selectedCityId = cityIds.get(position);
                        getDistrictData(selectedCityId);  // 加载对应城市的区数据
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                        spinnerDistrict.setAdapter(null);  // 清空区选择
                    }
                });
            }

            @Override
            public void onFailure(int statusCode, String message, Throwable error) {
                Log.e("test", "error code:" + statusCode + ", msg:" + message);
                Toast.makeText(locationDetailsInputActivity.this, "Failed to load city data: " + message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    // 获取区县数据
    private void getDistrictData(int cityId) {
        TencentSearch tencentSearch = new TencentSearch(this);
        DistrictChildrenParam districtChildrenParam = new DistrictChildrenParam();
        districtChildrenParam.id(cityId);  // 根据选中的城市 id 获取区数据

        tencentSearch.getDistrictChildren(districtChildrenParam, new HttpResponseListener<BaseObject>() {
            @Override
            public void onSuccess(int statusCode, BaseObject responseObject) {
                if (responseObject == null) {
                    return;
                }

                DistrictResultObject obj = (DistrictResultObject) responseObject;
                List<String> districts = new ArrayList<>();
                List<Integer> districtIds = new ArrayList<>();
                List<DistrictResultObject.DistrictResult> districtResults = obj.result.get(0);

                for (DistrictResultObject.DistrictResult result : districtResults) {
                    districts.add(result.fullname);
                    districtIds.add(result.id);
                }

                // 设置区适配器
                ArrayAdapter<String> districtAdapter = new ArrayAdapter<>(locationDetailsInputActivity.this,
                        android.R.layout.simple_spinner_item, districts);
                districtAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinnerDistrict.setAdapter(districtAdapter);
            }

            @Override
            public void onFailure(int statusCode, String message, Throwable error) {
                Log.e("test", "error code:" + statusCode + ", msg:" + message);
                Toast.makeText(locationDetailsInputActivity.this, "Failed to load district data: " + message, Toast.LENGTH_SHORT).show();
            }
        });
    }
}
